import { getCurrentPage, nextTick } from "miniprogram/miniprogram_npm/@vant/weapp/common/utils";
import APIZPZ from "../../../utils/apiZpz"

// pages/evaluate/model-evaluate/model-evaluate.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    progress: 0,
    activatedIndex: 0,// 必选进度
    modelName: undefined, // 机型名称
    modelId: undefined, // 机型id
    mouldId: undefined, // 估价模版id
    requiredQuestionCount: 0, // 必选的问题统计
    collapseQuestionList: <any>[], // 展示的问题列表
    allQuestionList: <any>[], //所有问题列表
    sumitBtnDisabled: true, // 提交按钮禁用
    optionTipVisible: false,//选项说明
    optionTipData: <any>{},
    oldTime: 0,
    scrollTop: 0,
    autoSubmitOnce: 1,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(data: any) {
    APIZPZ.getModelEvaluate(data.id).then((res: any) => {
      const data = res.data;
      let requiredQuestionCount = 0; // 必选问题数量统计
      data.questions = data.questions.map((item: any) => {
        if (item.requiredFlag === 1) {
          requiredQuestionCount += 1;
        }
        if (item.selectType === 0) {
          item.selectedId = '';
        } else {
          item.selectedIds = [];
        }
        return item;
      });
      this.setData({
        modelName: data.modelName,
        modelId: data.modelId,
        mouldId: data.mouldId,
        requiredQuestionCount,
        progressBar: 0,
        collapseQuestionList: [JSON.parse(JSON.stringify(data.questions[0]))],
        allQuestionList: JSON.parse(JSON.stringify(data.questions))
      });
    }).catch(() => {
      setTimeout(() => {
        wx.navigateBack({ delta: -1 });
      }, 1000);
    });
  },
  // 手风琴改变
  collapseChange(e: any) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      activatedIndex: this.data.activatedIndex === index ? '' : index
    })
  },
  // 单选改变
  singleSelected(e: any) {
    const data = e.currentTarget.dataset;
    if (data.choosable === 0) {
      return;
    }
    let name = '';
    let jump = '';
    // 设置选中的选项名字
    this.setData({
      collapseQuestionList: this.data.collapseQuestionList.map((q: any) => {
        if (data.questionid === q.id) {
          if (q.selectType === 0) {
            q.selectedId = data.optionid;
            q.options.filter((o: any) => {
              if (o.id === data.optionid) {
                jump = o.jump;
                name = o.optionName
              }
            });
            q.selectedOptionName = name;
          }
        }
        return q;
      }),
    });
    if (jump === 'jumpToNext' && this.data.activatedIndex + 1 === this.data.collapseQuestionList.length && this.data.collapseQuestionList.length < this.data.allQuestionList.length) {

      let requiredQuestionCount = 0; // 必选问题数量统计
      this.data.allQuestionList.map((item: any) => {
        if (item.requiredFlag === 1) {
          requiredQuestionCount += 1;
        }
      });
      this.setData({
        requiredQuestionCount,
        collapseQuestionList: [...this.data.collapseQuestionList, JSON.parse(JSON.stringify(this.data.allQuestionList[this.data.collapseQuestionList.length]))]
      });
      wx.nextTick(() => {
        this.setData({
          activatedIndex: this.data.activatedIndex + 1,
        });
      })
      console.log(this.data.activatedIndex)
    }
    if (jump === 'jumpToEnd') {
      this.data.collapseQuestionList.splice(this.data.activatedIndex + 1, this.data.collapseQuestionList.length - (this.data.activatedIndex + 1));
      this.setData({
        requiredQuestionCount: this.data.activatedIndex + 1,
        collapseQuestionList: this.data.collapseQuestionList
      });
      // wx.nextTick(() => {
      //   this.setData({
      //     activatedIndex: this.data.activatedIndex + 1,
      //   });
      // })
    }
    // 判断是否已选中所有必选项
    let requiredFlag = true;
    let progress = 0;
    this.data.collapseQuestionList.forEach((q: any) => {
      if (q.requiredFlag === 1 && !q.selectedId) {
        requiredFlag = false;
      } else if (q.requiredFlag === 1 && q.selectedId) {
        progress += 1;
      }
    });
    this.setData({
      progress
    })
    setTimeout(() => {
      this.setData({
        scrollTop: 9999
      })
    }, 1);
    if (requiredFlag) {
      this.setData({
        sumitBtnDisabled: false
      })
    }
  },
  multipleSelected(e: any) {
    const data = e.currentTarget.dataset;
    if (data.choosable === 0) {
      return;
    }
    const name = <any>[];
    this.setData({
      collapseQuestionList: this.data.collapseQuestionList.map((q: any) => {
        if (data.questionid === q.id && q.selectType === 1) {
          const index = q.selectedIds.findIndex((v: any) => v === data.optionid);
          if (index !== -1) {
            q.selectedIds.splice(index, 1);
          } else {
            q.selectedIds.push(data.optionid);
          }
          q.options.forEach((o: any) => {
            o.selected = false;
            if (q.selectedIds.findIndex((v: any) => v === o.id) !== -1) {
              name.push(o.optionName);
              o.selected = true;
            }
          });
          q.selectedOptionName = name.join(',');
        }
        return q;
      }),
    });
  },
  submit() {
    const time = new Date().getTime();
    if (time - this.data.oldTime < 1000) {
      return;
    }
    this.data.oldTime = time;
    const ids = <any>[];
    this.data.collapseQuestionList.forEach((q: any) => {
      if (q.selectType === 0) {
        ids.push(q.selectedId)
      } else {
        ids.push(...q.selectedIds)
      }
    });
    APIZPZ.getEvaluate({
      modelId: this.data.modelId,
      mouldId: this.data.mouldId,
      ids: ids.join(',')
    }).then((res: any) => {
      wx.navigateTo({ url: `/pages/order/submit-order/submit-order?price=${res.data.price}&evalId=${res.data.evalId}&modelName=${this.data.modelName}&modelId=${this.data.modelId}` });
    }).catch(()=>{
      this.data.autoSubmitOnce = 0;
    })
  },
  showOptionTip(e: any) {
    const data = e.currentTarget.dataset;
    console.log(data.option)
    this.setData({
      optionTipVisible: true,
      ['optionTipData.imgs']: data.option.optionImg ? data.option.optionImg.split(',') : [],
      ['optionTipData.optionName']: data.option.optionName,
      ['optionTipData.bak']: data.option.bak
    })
  },
  hideOptionTip() {
    this.setData({
      optionTipVisible: false,
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if(!this.data.sumitBtnDisabled&&wx.getStorageSync('token')&&this.data.autoSubmitOnce===0){
      this.data.autoSubmitOnce = 1;
      this.submit();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})